#!/bin/bash

WORKDIR=$(dirname $(realpath $0))

PRESETS=${WORKDIR}/presets

function print_menu()
{
    local choices=$*
    local count=${#choices[@]}

    local i=1
    for choice in $(echo $choices); do
        echo "     $i. $(basename ${choice})"
        i=$(($i+1))
    done
}

function link()
{
    file=$1
    file=$(realpath ${file})

    \rm -f ${WORKDIR}/.tmp.config.mk
    ln -rsf ${file} ${WORKDIR}/.tmp.config.mk
    echo "Using .tmp.config.mk -> $(basename ${file})"
    # echo "Using $(stat -c '%N' ${WORKDIR}/.tmp.config.mk)"
}

array=($(ls ${PRESETS}/*.mk | sort))
# string to array
# array=(${array// / })

if [[ $# -ge 1 ]]; then
    target=$1
    if [ -f ${target} ]; then
        if [ -f ${WORKDIR}/.tmp.config.mk ]; then
            echo ".tmp.config.mk -> $(basename $(realpath ${WORKDIR}/.tmp.config.mk))"
        fi

        link ${target}
        exit 0
    fi
    if [ -f ${PRESETS}/${target} ]; then
        if [ -f ${WORKDIR}/.tmp.config.mk ]; then
            echo ".tmp.config.mk -> $(basename $(realpath ${WORKDIR}/.tmp.config.mk))"
        fi

        link ${PRESETS}/${target}
        exit 0
    fi

    if [ $(echo -n ${target} | grep -e "^[0-9][0-9]*$") ]; then
        if [ ${target} -le ${#array[@]} ]; then
            # array in zsh starts from 1 instead of 0.
            if [ -z "${ZSH_VERSION}" ]; then
                target=$(expr ${target} - 1)
            fi
            target=${array[${target}]}
            if [ -f ${target} ]; then
                if [ -f ${WORKDIR}/.tmp.config.mk ]; then
                    echo ".tmp.config.mk -> $(basename $(realpath ${WORKDIR}/.tmp.config.mk))"
                fi

                link ${target}
                exit 0
            fi
        else
            echo "Error: no such index: ${target}, max: ${#array[@]}"
            exit 1
        fi
    fi

    echo "Error: no such file: ${target}"
    exit 1
fi

if [ -f ${WORKDIR}/.tmp.config.mk ]; then
    echo "current: .tmp.config.mk -> $(basename $(realpath ${WORKDIR}/.tmp.config.mk))"
fi

echo "select from:"
# echo ${array[@]} | xargs -n 1 | sed "=" | sed "N;s/\n/. /"
print_menu ${array[@]}
read -p "Please input index: " index

# array in zsh starts from 1 instead of 0.
if [ -z "${ZSH_VERSION}" ]; then
    index=$(expr ${index} - 1)
fi

set -e

target=${array[${index}]}

if [ -f ${target} ]; then
    link ${target}
    exit 0
fi
echo "Error: no such index: ${target}, max: ${#array[@]}"
exit 1
